"""
Web
"""

import streamlit as st
import threading
import time
from src.web.components.header import Header
from src.web.components.progress_bar import ProgressBar
from src.core.video_processor import VideoProcessor
from src.core.transcriber import WhisperTranscriber
from src.core.summarizer import VideoSummarizer
from src.core.ollama_client import OllamaClient

class ProcessingPage:
    """"""
    
    def __init__(self):
        self.video_processor = VideoProcessor()
        self.transcriber = None
        self.summarizer = None
        self.progress_bar = None
    
    def render(self):
        """"""
        # 
        Header.render()
        
        st.header(" ")
        
        # 
        if 'uploaded_file_path' not in st.session_state:
            st.error(" ")
            if st.button(" "):
                st.session_state.current_page = 'upload'
                st.rerun()
            return
        
        # 
        if 'video_info' in st.session_state:
            video_info = st.session_state.video_info
            st.info(f" : {video_info.get('original_name', '')}")
        
        # 
        self.progress_bar = ProgressBar().render()
        
        # 
        status_container = st.container()
        
        # 
        if not st.session_state.get('processing', False):
            st.session_state.processing = True
            
            # 
            processing_thread = threading.Thread(
                target=self._process_video,
                args=(st.session_state.uploaded_file_path, st.session_state.settings)
            )
            processing_thread.daemon = True
            processing_thread.start()
        
        # 
        self._check_processing_status(status_container)
    
    def _process_video(self, file_path, settings):
        """"""
        try:
            # 1: 
            self._update_progress(10, " ...")
            audio_path = self.video_processor.extract_audio(file_path)
            
            # 2: 
            self._update_progress(20, " Whisper...")
            self.transcriber = WhisperTranscriber(
                model_name=settings['whisper_model'],
                device=settings.get('device', 'auto')
            )
            
            # 3: 
            self._update_progress(30, " ...")
            
            def progress_callback(progress):
                self._update_progress(30 + int(progress * 0.4), f" : {progress:.1%}")
            
            transcript_result = self.transcriber.transcribe_file(
                audio_path,
                language=settings['language'] if settings['language'] != 'auto' else None,
                progress_callback=progress_callback
            )
            
            # 4: 
            if not settings.get('transcript_only', False):
                self._update_progress(70, " Ollama...")
                
                host = settings.get('ollama_host', 'localhost')
                port = settings.get('ollama_port', 11434)
                ollama_client = OllamaClient(base_url=f"http://{host}:{port}")
                self.summarizer = VideoSummarizer(
                    ollama_client=ollama_client,
                    model_name=settings['ollama_model']
                )
                
                self._update_progress(80, " AI...")
                
                summary_result = self.summarizer.generate_summary(
                    transcript_result['text'],
                    style=settings['summary_style'],
                    extract_keywords=settings.get('enable_keywords', True),
                    create_chapters=settings.get('enable_chapters', True)
                )
            else:
                summary_result = None
            
            # 5: 
            self._update_progress(90, " ...")
            
            result_data = {
                'transcript': transcript_result,
                'summary': summary_result,
                'settings': settings,
                'video_info': st.session_state.get('video_info', {})
            }
            
            # session state
            st.session_state.result = result_data
            st.session_state.processing = False
            st.session_state.processing_complete = True
            
            self._update_progress(100, " ")
            
        except Exception as e:
            st.session_state.processing = False
            st.session_state.processing_error = str(e)
            self._update_progress(0, f" : {e}")
    
    def _update_progress(self, value, message):
        """"""
        if hasattr(st.session_state, 'progress_value'):
            st.session_state.progress_value = value
        else:
            st.session_state.progress_value = value
        
        if hasattr(st.session_state, 'progress_message'):
            st.session_state.progress_message = message
        else:
            st.session_state.progress_message = message
    
    def _check_processing_status(self, status_container):
        """"""
        # 
        if hasattr(st.session_state, 'progress_value'):
            self.progress_bar.update(
                st.session_state.progress_value,
                st.session_state.get('progress_message', '')
            )
        
        # 
        if st.session_state.get('processing_complete', False):
            with status_container:
                st.success(" ")
                
                col1, col2 = st.columns(2)
                
                with col1:
                    if st.button(" ", type="primary", use_container_width=True):
                        st.session_state.current_page = 'result'
                        st.rerun()
                
                with col2:
                    if st.button(" ", use_container_width=True):
                        # 
                        self._cleanup_session_state()
                        st.session_state.current_page = 'upload'
                        st.rerun()
        
        # 
        elif st.session_state.get('processing_error'):
            with status_container:
                st.error(f" : {st.session_state.processing_error}")
                
                col1, col2 = st.columns(2)
                
                with col1:
                    if st.button(" ", type="primary", use_container_width=True):
                        # 
                        del st.session_state.processing_error
                        st.session_state.processing = False
                        st.rerun()
                
                with col2:
                    if st.button(" ", use_container_width=True):
                        self._cleanup_session_state()
                        st.session_state.current_page = 'upload'
                        st.rerun()
        
        # 
        elif st.session_state.get('processing', False):
            with status_container:
                st.info("⏳ ...")
                
                # 
                time.sleep(1)
                st.rerun()
    
    def _cleanup_session_state(self):
        """session state"""
        keys_to_remove = [
            'processing', 'processing_complete', 'processing_error',
            'progress_value', 'progress_message', 'uploaded_file_path',
            'video_info', 'result'
        ]
        
        for key in keys_to_remove:
            if key in st.session_state:
                del st.session_state[key]